import { notEmpty } from '@/utils'

const lng = (value) => {
  let errInfo = ''
  if (typeof value === 'number' && Number.isNaN(value)) {
    errInfo = '格式不正确'
  } else if (notEmpty(value)) {
    value = value.toString()
    if (/^-?(\d+|\d+\.\d+)$/.test(value)) {
      value = Number(value)
      if (value > 180 || value < -180) {
        errInfo = '经度的范围为[-180, 180]'
      }
    } else {
      errInfo = '格式不正确'
    }
  }

  return errInfo
}

const lat = (value) => {
  let errInfo = ''
  if (typeof value === 'number' && Number.isNaN(value)) {
    errInfo = '格式不正确'
  } else if (notEmpty(value)) {
    value = value.toString()
    if (/^-?(\d+|\d+\.\d+)$/.test(value)) {
      value = Number(value)
      if (value > 90 || value < -90) {
        errInfo = '纬度的范围为[-90, 90]'
      }
    } else {
      errInfo = '格式不正确'
    }
  }

  return errInfo
}

export default {
  lng: {
    validator(rule, value, callback) {
      const errInfo = lng(value)
      callback(errInfo ? new Error(errInfo) : undefined)
    }
  },
  lat: {
    validator(rule, value, callback) {
      const errInfo = lat(value)
      callback(errInfo ? new Error(errInfo) : undefined)
    }
  },
}
